package com.yaan.commons.utils;

import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

public class RedisUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource(name = "redisTemplate")
    private ValueOperations<String,String> valueOperations;

    //默认过期时间
    private static final long DEFAULT_EXPIRE = 60 * 60 * 24;

    //代表不过期
    private static final long No_EXPIRE = -1;

    private Gson gson = new Gson();

    //对象装换成json字符串
    private String getJsonStr(Object object){
        if (object instanceof Integer || object instanceof Double || object instanceof Float ||
            object instanceof Boolean || object instanceof Long || object instanceof Character){
            return  String.valueOf(object);
        }
        return gson.toJson(object);
    }

    //将Json字符串装换成对象
    private <T> T getObject(String jsonstr,Class<T> clazz){
        return gson.fromJson(jsonstr,clazz);
    }

    //存入对象并设置过期时间(秒为单位)
    public void set(String key,Object value,Long expire){
        valueOperations.set(key,getJsonStr(value));
        if (No_EXPIRE!=expire){
            redisTemplate.expire(key,expire, TimeUnit.SECONDS);
        }
    }

    //存入对象如果没设置过期时间,将会设置默认过期时间(秒为单位)
    public void set(String key,Object value){
        set(key,value,DEFAULT_EXPIRE);
    }

    //根据key获取value并返回,并设置过期时间(秒为单位)
    public String get(String key,Long expire){
        String str = valueOperations.get(key);
        if (No_EXPIRE!=expire){
            redisTemplate.expire(key,expire,TimeUnit.SECONDS);
        }
        return str;
    }

    //根据key获取value,如果没设置过期时间,将会设置为不过期(秒为单位)
    public String get(String key){
        return get(key,No_EXPIRE);
    }

    //根据key获取value并转换为对象,并设置过期时间(秒为单位)
    public <T> T get(String key,Class<T> clazz,Long expire){
        String str = valueOperations.get(key);
        if (No_EXPIRE!=expire){
            redisTemplate.expire(key,expire,TimeUnit.SECONDS);
        }
        return str == null?null:getObject(str,clazz);
    }

    //根据key获取value并转换为对象,如果没设置过期时间,将会设置为不过期(秒为单位)
    public <T> T get(String key,Class<T> clazz){
        return get(key,clazz,No_EXPIRE);
    }

    //删除指定的key
    public void delete(String key){
        redisTemplate.delete(key);
    }
}
